package com.artisan.web.action;

import com.artisan.commonweb.result.ActionResult;
import com.artisan.medium.admin.pojo.ShiroUser;
import com.artisan.model.User;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yang on 2017/7/1.
 */
@Controller
@RequestMapping("/admin/login/")
public class LoginController extends BaseController{
    private static final Logger log = LogManager.getLogger(LoginController.class);

    @RequestMapping("loginView")
    public ModelAndView loginView(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Integer> result = new HashMap<>();
        return new ModelAndView("/login", result);
    }

    @RequestMapping("loginToMain")
    @ResponseBody
    public ActionResult loginToMain(HttpServletRequest request){
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        ActionResult actionResult=new ActionResult();
        Subject subject= SecurityUtils.getSubject();
        actionResult.setCode(200);
        actionResult.setHint("登录成功！");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{

            subject.login(token);// 登录
        }catch (UnknownAccountException unknownAccountException){
            actionResult.setCode(500);
            actionResult.setHint("用户名或密码错误！");
            System.out.print("用户名或密码错误");
        }catch (DisabledAccountException disabledAccountException){
            actionResult.setCode(500);
            actionResult.setHint("账号锁定！");
            System.out.print("账号锁定");
        }
        User shiroUser=super.getShiroUser();
        if(null!=shiroUser){
            //操作httpSession
            request.getSession().setAttribute("SESSION_USERNAME",shiroUser.getNickName());
            actionResult.setData(shiroUser.getRoleId());
        }
        return actionResult;
    }
    /**
     * 退出登录
     * */
    @RequestMapping("logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/admin/login/loginView.do";
    }
}
